/*
XPTracker - Alternative Agile Tracking Tool
Copyright (C) 2006-2009  Stephen Starkey

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
*/
package org.xptracker.web;

import com.google.inject.Inject;
import org.xptracker.domain.Queue;
import org.xptracker.domain.Story;
import org.xptracker.domain.User;
import org.xptracker.services.EmailService;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class QueueNotifier {
  private static final String SUMMARY_FMT = "XPTracker - Change to Queue ''{0}''";
  private static final String BODY_FMT = "{0} was {1}.\n\nReason: {2}";
  private List<Message> messages = new ArrayList<Message>();

  @SuppressWarnings({"UnusedDeclaration"})
  @Inject
  private EmailService emailService;

  public void storyRemoved(Queue queue, Story story, String reason) {
    addMessage("removed", queue, story, reason);
  }

  public void storyAdded(Queue queue, Story story, String reason) {
    addMessage("added", queue, story, reason);
  }

  private void addMessage(String action, Queue queue, Story story, String reason) {
    messages.add(new Message(queue,
        MessageFormat.format(BODY_FMT, story.toString(), action, reason)));
  }

  public void sendNotifications(User from) {
    Map<Queue, StringBuilder> bodies = new HashMap<Queue, StringBuilder>();

    for(Message msg: messages) {
      StringBuilder builder = bodies.get(msg.getQueue());
      if (builder == null) {
        builder = new StringBuilder();
        bodies.put(msg.getQueue(), builder);
      }
      builder.append(msg.getBody()).append("\n\n");
    }

    for(Queue queue: bodies.keySet()) {
      String summary = MessageFormat.format(SUMMARY_FMT, queue.getName());
      emailService.sendEmail(from, queue.getTrackers(), summary, bodies.get(queue).toString().trim());
    }
  }

  private static class Message {
    private Queue queue;
    private String body;

    public Message(Queue queue, String body) {
      this.queue = queue;
      this.body = body;
    }

    public String getBody() {
      return body;
    }

    public Queue getQueue() {
      return queue;
    }
  }
}
